package com.zhonglz.api.file;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import com.zhonglz.util.file.FileUtils;
import com.zhonglz.util.hex.HexUtils;
import com.zhonglz.util.sm4.Sm4Utils;
import com.zhonglz.util.tools.RandomUtils;

/***
 * 文件sm4对称加密存储
 * @author zhonglz
 *
 */
public class TestFileSm4ToLocal {

	private static String sm4Key = "e2027601d8890194c6362d8447204098";//sm4加减密key，初始化加载静态方法赋值
	private static boolean isUse = false;//是否使用默认的sm4Key  true开启 
	
	private static String fileId = RandomUtils.randomNumber(16);//随机获取一个文件名id
	static {
		System.out.println("-----------------文件加密初始化--开始-------------------");
		Security.addProvider(new BouncyCastleProvider());
		String str;
		try {
			if(!isUse) {
				str = HexUtils.encodeHex(Sm4Utils.generateKey());
				System.out.println("生成SM4对称算法的key:"+str);//生成数位KEY
				sm4Key = str;
			}
			System.out.println("文件id变量赋值:"+fileId);
			System.out.println("sm4Key变量赋值成功:"+sm4Key);
		} catch (Exception e) {
			e.getMessage();
		}
		System.out.println("-----------------文件加密初始化--结束-------------------");
	}
	
	public static void main(String[] args) throws Exception {
		byte[] sm4KeyDate = HexUtils.decodeHex(sm4Key);
		System.out.println("-----------------文件加密开始-------------------");
		String yuanFilePath = "C:\\Users\\Administrator\\Desktop\\123\\源文件.pdf";
		String sm4FilePath = "C:\\Users\\Administrator\\Desktop\\123\\加密"+fileId+".temp";
		System.out.println("文件加密：读取原始文件，地址："+yuanFilePath);
		//获取文件的字节数组
		byte[] yuanFileByte =FileUtils.file2byte(new File(yuanFilePath));
		//加密字节数组
		byte[] sm4FileByte=Sm4Utils.encryptEcbPadding(sm4KeyDate,yuanFileByte);
		//写入本机地址
		InputStream is = new ByteArrayInputStream(sm4FileByte);
		FileUtils.writeToLocal(sm4FilePath, is);
		System.out.println("文件加密：文件sm4对称加密后地址："+sm4FilePath);
		System.out.println("-----------------文件加密结束-------------------");
		
		
		
		System.out.println("-----------------文件解密开始-------------------");
		String jiemiFilePath = "C:\\Users\\Administrator\\Desktop\\123\\解密"+fileId+".pdf";
		System.out.println("文件加密：读取加密文件，地址："+sm4FilePath);
		byte[] sm4YuanFileByte =FileUtils.file2byte(new File(sm4FilePath));
		byte[] sm4JieMiFileByte=Sm4Utils.decryptEcbPadding(sm4KeyDate,sm4YuanFileByte);
		//写入本机地址
		InputStream iss = new ByteArrayInputStream(sm4JieMiFileByte);
		FileUtils.writeToLocal(jiemiFilePath, iss);
		System.out.println("文件解密：文件sm4对称解密后地址："+jiemiFilePath);
		System.out.println("-----------------文件解密结束-------------------");
	}
	
}
